<?php
namespace App\Api\Controllers\Lianhou;

use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\RefundOrder;
use App\Models\UserWalletDetail;
use Illuminate\Support\Facades\Log;

class LogicController extends BaseController
{
    public function __construct()
    {

    }

    public function qrSubmitParams ($data_insert, $data)
    {
        $payConfig = new \App\Api\Controllers\Config\LianhouPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '联厚支付配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '联厚支付商户号不存在'
            ]);
        }
        //支付宝
        if ($data['ways_type'] == '80002') {
            $out_trade_no = 'ali_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '支付宝';
            $data_insert['ways_source'] = 'alipay';
            $data_insert['ways_source_desc'] = '支付宝';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //云闪付
        if ($data['ways_type'] == '80003') {
            $out_trade_no = 'un_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '银联支付';
            $data_insert['ways_source'] = 'unionpay';
            $data_insert['ways_source_desc'] = '银联支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //微信
        if ($data['ways_type'] == '80001') {
            $out_trade_no = 'wx_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '微信支付';
            $data_insert['ways_source'] = 'weixin';
            $data_insert['ways_source_desc'] = '微信支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        $payData = [
            'mch_id'       => $merchant->mch_id,
            'term_no'      => $merchant->term_no,
            'platform_id'  => $config->platform_id,
            'total_amount' => $data['total_amount'],
            'out_trade_no' => $out_trade_no,
        ];

        $return = (new PayController())->qr_submit($payData, $config);
        if ($return['status'] == 1) {
            $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }
            return json_encode([
                'status' => 1,
                'data' => $return['data']
            ]);
        } else {
            return json_encode([
                'status' => 2,
                'message' => $return['message']
            ]);
        }
    }


    public function payParams ($data_insert, $data)
    {
        $store_id = $data['store_id'] ?? '';
        $store_pid = $data['store_pid'] ?? '';
        $merchant_id = $data['merchant_id'] ?? '';
        $total_amount = $data['total_amount'] ?? '';
        $ways_type = $data['ways_type'] ?? '';
        $store_name = $data['store_name'] ?? '';
        $config_id = $data['config_id'] ?? '';
        $ways_type_desc = $data['ways_type_desc'] ?? '';
        $ways_source = $data['ways_source'] ?? '';
        $title = $data['title'] ?? '';
        $tg_user_id = $data['tg_user_id'] ?? '';
        $out_trade_no = $data['out_trade_no'] ?? '';
        $code = $data['code'] ?? '';
        $company = $data['company'] ?? '';
        $ways_source_desc = $data['ways_source_desc'] ?? '';
        $device_id = $data['device_id'] ?? ''; //终端设备号.注:当中国银联时,为必填



        $payConfig = new \App\Api\Controllers\Config\LianhouPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '联厚支付配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '联厚支付商户号不存在'
            ]);
        }

        //入库参数
        $data_insert['out_trade_no'] = $out_trade_no;
        $data_insert['ways_type'] = $ways_type;
        $data_insert['ways_type_desc'] = $ways_type_desc;
        $data_insert['ways_source'] = $ways_source;
        $data_insert['company'] = $company;
        $data_insert['ways_source_desc'] = $ways_source_desc;

        $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
        if (!$insert_re) {
            return json_encode([
                'status' => 2,
                'message' => '订单未入库'
            ]);
        }
        $payData = [
            "mch_id" => $merchant->mch_id,
            'term_no' => $merchant->term_no,
            "out_trade_no" => $out_trade_no,
            "desc" => $title,
            "terminal_id" => $device_id,
            "total_amount" => $total_amount,
            "code" => $code
        ];


        $return = (new PayController())->scan_pay($payData, $config);

        //返回支付成功
        if ($return['status'] == 1) {
            $trade_no = isset($return['data']['orderNo']) ? $return['data']['orderNo'] : '';
            $buyer_user_id = $return['data']['OpenId'] ?? ''; //

            $pay_time = $return['payTime'];
            $buyer_pay_amount = $return['data']['payAmount'];

            $update_data = [
                'trade_no' => $trade_no,
//                'other_no' => $other_no,
                'buyer_id' => $buyer_user_id,
                'status' => '1',
                'pay_status_desc' => '支付成功',
                'pay_status' => 1,
                'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                'pay_time' => $pay_time,
                'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
            ];
            (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $out_trade_no);

            //支付成功后的动作
            $data = [
                'ways_type' => $data['ways_type'],
                'ways_type_desc' => $data['ways_type_desc'],
                'company' => $data_insert['company'],
                'source_type' => '80001', //返佣来源
                'source_desc' => '联厚', //返佣来源说明
                'total_amount' => $total_amount,
                'other_no' => $data_insert['other_no'],
                'out_trade_no' => $out_trade_no,
                'rate' => $data_insert['rate'],
                'fee_amount' => $data_insert['fee_amount'],
                'merchant_id' => $merchant_id,
                'store_id' => $store_id,
                'user_id' => $tg_user_id,
                'config_id' => $config_id,
                'store_name' => $store_name,
                'ways_source' => $data['ways_source'],
                'pay_time' => $pay_time,
                'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
            ];
            PaySuccessAction::action($data);

            return json_encode([
                'status' => 1,
                'pay_status' => '1',
                'message' => '支付成功',
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'ways_type' => $ways_type,
                    'total_amount' => $total_amount,
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'config_id' => $config_id,
                    'pay_time' => $pay_time,
                    'trade_no' => $trade_no,
                    'ways_source' => $data['ways_source'],
                ]
            ]);
        } elseif ($return['status'] == 2) {
            return json_encode([
                'status' => 1,
                'pay_status' => 2,
                'message' => '支付中',
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'ways_type' => $ways_type,
                    'ways_source' => $data['ways_source'],
                    'total_amount' => $total_amount,
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'config_id' => $config_id,
                ]
            ]);
        } else {
            return json_encode([
                'status' => 2,
                'message' => $return['message']
            ]);
        }
    }

    public function queryParams ($store_id, $store_pid, $data, $order)
    {
        try {
            $payConfig = new \App\Api\Controllers\Config\LianhouPayConfigController();
            $config = $payConfig->config($data['config_id']);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '联厚支付配置不存在请检查配置'
                ]);
            }
            $merchant = $payConfig->merchant($store_id, $store_pid);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '联厚支付商户号不存在'
                ]);
            }
    
    
            $payData = [
                "mch_id" => $merchant->mch_id,
                "out_trade_no" => $order->out_trade_no
            ];
            $return = (new PayController())->order_query($payData, $config);

            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = isset($return['data']['orderNo']) ? $return['data']['orderNo'] : '';
                $buyer_user_id = $return['data']['OpenId'] ?? ''; //

                $pay_time = $return['data']['payTime'];
                $buyer_pay_amount = $return['data']['payAmount'];
                if ($order->pay_status != 1) {
                    $update_data = [
                        'trade_no' => $trade_no,
    //                'other_no' => $other_no,
                        'buyer_id' => $buyer_user_id,
                        'status' => '1',
                        'pay_status_desc' => '支付成功',
                        'pay_status' => 1,
                        'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                        'pay_time' => $pay_time,
                        'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
                    ];
                    (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $order->out_trade_no);
    
                    //支付成功后的动作
                    $data = [
                        'ways_type' => $order->ways_type,
                        'ways_type_desc' => $order->ways_type_desc,
                        'company' => $order->company,
                        'source_type' => '80001', //返佣来源
                        'source_desc' => '联厚', //返佣来源说明
                        'total_amount' => $order->total_amount,
                        'other_no' => $order->other_no,
                        'out_trade_no' => $order->out_trade_no,
                        'rate' => $order->rate,
                        'fee_amount' => $order->fee_amount,
                        'merchant_id' => $order->merchant_id,
                        'store_id' => $store_id,
                        'user_id' =>  $order->user_id,
                        'config_id' => $order->config_id,
                        'store_name' =>  $order->store_name,
                        'ways_source' =>  $order->ways_source,
                        'pay_time' => $pay_time,
                        'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                    ];
                    PaySuccessAction::action($data);
                }
                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $order->config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        'ways_source' => $order->ways_source,
                    ]
                ]);
            } //支付中
            elseif ($return['status'] == 2) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => '支付中',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'ways_source' => $order->ways_source,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $order->config_id
                    ]
                ]);
            }
            else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
         } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }

    public function refundParams($data, $order)
    {
        $payConfig = new \App\Api\Controllers\Config\LianhouPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '联厚支付配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '联厚支付商户号不存在'
            ]);
        }
        $count = RefundOrder::where(['out_trade_no' => $data['out_trade_no']])->count();

        $payData = [
            "out_trade_no" => $order->out_trade_no,
            "refund_amount" => $data['refund_amount'],
            "refund_no" => $data['refund_no'].$count
        ];

        $return = (new PayController())->refund($payData, $config);

        //退款请求成功
        if ($return['status'] == '1') {
            $insert_data = [
                'status' => '6',
                'pay_status' => 6,
                'pay_status_desc' => '已退款',
                'refund_amount' => $data['new_refund_amount'],
                'fee_amount' => $data['new_fee_amount']
            ];
            $this->update_day_order($insert_data, $data['out_trade_no']);

            RefundOrder::create([
                'ways_source' => $order->ways_source,
                'type' => $data['ways_type'],
                'refund_amount' => $data['refund_amount'], //退款金额
                'refund_no' => $payData['refund_no'], //平台退款单号
                'store_id' => $data['store_id'],
                'merchant_id' => $data['merchant_id'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_no' => $order->trade_no
            ]);
            //退款成功后的操作
            RefundSuccessAction::action([
                'out_trade_no'=>$data['out_trade_no'],
                'refund_no' => $payData['refund_no'], //平台退款单号
            ]);

            //返佣去掉
            UserWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                'settlement' => '03',
                'settlement_desc' => '退款订单'
            ]);
            MerchantWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                'settlement' => '03',
                'settlement_desc' => '退款订单'
            ]);

            $data = [
                'refund_amount' => $data['refund_amount'],
                'out_trade_no' => $data['out_trade_no'],
                'refund_no' => $payData['refund_no'], //平台退款单号
                'other_no' => $order->trade_no
            ];
            return json_encode([
                'status' => '1',
                'message' => '退款成功',
                'data' => $data
            ]);
        } //退款处理中
        elseif($return['status'] == '3') {
            $insert_data = [
                'status' => '5',
                'pay_status' => 5,
                'pay_status_desc' => '退款中'
            ];
            $res = $this->update_day_order($insert_data, $data['out_trade_no']);
            if (!$res) {
                Log::info('威富通-退款中-更新失败');
            }

            $refund_count = $return['data']['refund_count']-1; //退款记录数
            $data = [
                'refund_amount' => $data['refund_amount'],
                'out_trade_no' => $data['out_trade_no'],
                'refund_no' => $return['data']['refund_id_'.$refund_count], //平台退款单号
                'other_no' => $data['other_no']
            ];
            return json_encode([
                'status' => '1',
                'message' => '退款中',
                'data' => $data
            ]);
        }
        else {
            //其他情况
            $message = $return['message'];
            return json_encode([
                'status' => '2',
                'message' => $message
            ]);
        }
    }





}
